import {_decorator} from 'cc';
import {Pack, PackCodec} from "./Pack";
import {ProtoDispatcher} from "./ProtoDispatcher";
import Singleton from "db://assets/scripts/common/Singleton";

const {ccclass, property} = _decorator;

@ccclass('NetManager')
export class NetManager extends Singleton {

    private _socket: WebSocket = null;


    init() {
        if (this._socket != null) {
            return;
        }
        this._socket = new WebSocket("ws://localhost:9999/websocket");
        this._socket.binaryType = "arraybuffer";
        this._socket.onopen = this.onOpen;
        this._socket.onclose = this.onClose;
        this._socket.onerror = this.onError;
        this._socket.onmessage = this.onMessage;
    }

    public sendMsg(message: any) {
        if (this._socket && this._socket.readyState == WebSocket.OPEN) {
            this._socket.send(message);
        } else {
            console.log("WebSocket is not open.");
        }
    }

    private onOpen() {
        console.log("socket onopen");
    }

    private onMessage(event: MessageEvent) {
        // 解码
        let pack: Pack = PackCodec.decode(new Uint8Array(event.data));
        console.log("socket onmessage", pack, event);
        ProtoDispatcher.getInstance().dispatch(pack);
    }

    private onError(event: Event) {
        console.log("socket onerror", event);
    }

    private onClose(event: CloseEvent) {
        console.log("socket onclose", event.reason);
    }

}



